package channelService

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelStatus"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/ChanSyncObj"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"sync"
)

type channelService struct {
	deviceKeyMap sync.Map
}

func (e *channelService) OpenChannel(channelName string, channelParam map[string]interface{}) error {
	deviceKey := Map.GetString(channelParam, "deviceKey", "")

	channelStatus.Param.UpdateParamStatus(channelName, "deviceKey", deviceKey != "")

	// 必选项
	if Method.HasEmpty(deviceKey) {
		return errors.New("参数不能为空: deviceKey")
	}

	// 保存deviceKey和channelName的关系
	e.deviceKeyMap.Store(deviceKey, channelName)

	// 为通道创建一个多线程消息交换的chan
	ChanSyncObj.Instance(deviceKey)
	return nil
}

func (e *channelService) CloseChannel(channelName string, channelParam map[string]interface{}) error {
	deviceKey := Map.GetString(channelParam, "deviceKey", "")

	// 删除deviceKey和channelName的关系
	e.deviceKeyMap.Delete(deviceKey)

	// 释放掉为该通道创建的多线程之间消息交换的chan
	ChanSyncObj.Release(deviceKey)
	return nil
}

func (e *channelService) Execute(requestVO *commRedisRpc.ChannelRequestVO) (*commRedisRpc.ChannelRespondVO, error) {
	return nil, errors.New("不支持Execute操作")
}
func (e *channelService) Report() ([]*commRedisRpc.ChannelRespondVO, error) {
	return report.popAll(commEnv.Service.ModelName)
}
